import { OnInit, Component, Output, EventEmitter, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { TeacherSerivce } from 'src/app/project/service/icm/icm-system-user/teacher/teacher.service';
import { FormBuilder, Validators, NgForm, FormGroup, FormControl, ValidationErrors } from '@angular/forms';
import { OperationNotification, OperationType } from 'src/app/project/model/common/operation-notification';
import { TeacherDTO } from 'src/app/project/model/icm/icm-system-user/teacher/teacher.dto';
import { QueryOptions } from 'src/app/project/model/common/query-options';
import { Observable, Observer } from 'rxjs';
import { FormUtil } from '@shared/utils/form-util';
import { format } from 'date-fns';
import { ConfigurationService } from 'src/app/project/service/icm/icm-global/configuration/configuration.service';

@Component({
  selector: 'app-teacher-detail',
  templateUrl: './teacher-detail.component.html',
  styles: [],
})
export class TeacherDetailComponent implements OnInit {
  constructor(
    private msg: NzMessageService,
    private teacherService: TeacherSerivce,
    private fb: FormBuilder,
    private configurationService: ConfigurationService,
  ) {
    this.validateForm = this.fb.group({
      code: ['', [Validators.required], [this.codeAsyncValidator]],
      name: ['', [Validators.required]],
      identity: ['', [Validators.required]],
      gender: [0, [Validators.required]],
      degreeType: [0, [Validators.required]],
      joinTime: [0, [Validators.required]],
      birthDate: [''],
    });
  }

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<TeacherDTO>>();

  /**
   * form组件
   */
  @ViewChild('myForm', { static: false })
  public myForm: NgForm;

  /**
   * 表单
   */
  validateForm: FormGroup;

  /**
   * 是否预览
   */
  isPreView = false;

  /**
   * 表单窗体打开/关闭控制
   */
  isVisible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 分页参数初始化
   */
  queryOptions: QueryOptions = {
    page: 0,
    size: 20,
    sort: 'id,asc',
  };

  /**
   * 教师信息
   */
  teacher: TeacherDTO = {
    id: null,
    code: '',
    name: '',
    gender: '',
    degreeType: '',
    birthDate: '',
    joinTime: '',
    isSenator: false,
    isInstructor: false,
  };

  /**
   * 教师身份: 辅导员、教务员、科任教师
   */
  identity: string;
  /**
   * 是否添加教务员
   */
  isCreateSenator = false;
  /**
   * 教师编码是否已存在，true为已存在
   */
  isExist: boolean;
  /**
   * 新建教师的默认密码
   */
  defualtPW = null;
  /**
   * 校验教师编码
   */
  codeAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      setTimeout(() => {
        this.teacherService.checkoutCodeIsExist(control.value).subscribe(data => {
          this.isExist = data.data;
        });
        if (this.isExist) {
          observer.next({ error: true, duplicated: true });
        } else if (control.value.includes(' ')) {
          observer.next({ error: true, blank: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 1000);
    });

  /**
   * 修改窗口状态
   */
  handleCancel() {
    this.isVisible = false;
    FormUtil.resetForm(this.myForm.form);
  }

  /**
   * 修改或新增教师信息
   * @param isPreView 是否预览
   * @param item 教师信息
   * @param isSenator 是否添加教务员
   */
  edit(isPreView: boolean, item: TeacherDTO, isSenator?: true) {
    this.isPreView = isPreView;
    this.teacher = this.initTeacher(item);
    // 判断身份
    this.identity =
      this.teacher.isSenator === true ? 'isSenator' : this.teacher.isInstructor === true ? 'isInstructor' : 'isTeacher';
    if (isSenator) {
      this.isCreateSenator = true;
      this.identity = 'isSenator';
    }
    this.isVisible = true;
  }

  /**
   * 初始化教师
   */
  initTeacher(item: TeacherDTO): TeacherDTO {
    return {
      id: item ? item.id : null,
      name: item ? item.name : '',
      code: item ? item.code : '',
      gender: item ? item.gender : null,
      degreeType: item ? item.degreeType : null,
      birthDate: item ? item.birthDate : '',
      joinTime: item ? item.joinTime : '',
      isSenator: item ? item.isSenator : false,
      isInstructor: item ? item.isInstructor : false,
      academyId: item ? item.academyId : null,
      academyName: item ? item.academyName : '',
    };
  }

  /**
   * 保存前验证数据
   */
  beforeSave() {
    if (!this.teacher.academyId) {
      this.msg.error('所属学院必选');
      return false;
    }
    if (this.teacher.code === '') {
      this.msg.error('教师编码必填');
      return false;
    }
    if (this.teacher.name === '') {
      this.msg.error('教师名称必填');
      return false;
    }
    if (!this.teacher.gender) {
      this.msg.error('性别必选');
      return false;
    }
    if (!this.teacher.degreeType) {
      this.msg.error('学历必选');
      return false;
    }
    if (this.teacher.joinTime === '') {
      this.msg.error('入职时间必填');
      return false;
    } else {
      this.teacher.joinTime = format(this.teacher.joinTime, 'YYYY-MM-DD');
    }
    if (this.identity === '') {
      this.msg.error('教师身份必选');
      return false;
    }
    this.teacher.birthDate = format(this.teacher.birthDate, 'YYYY-MM-DD');
    this.teacher.isSenator = this.identity === 'isSenator';
    this.teacher.isInstructor = this.identity === 'isInstructor';
    return true;
  }

  /**
   * 保存
   */
  save() {
    if (!this.beforeSave()) {
      return;
    }
    this.loading = true;
    if (!this.teacher.id) {
      // id为空，为新建
      this.teacherService.create(this.teacher).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('保存失败，请重试'),
        () => this.afterCallCompleted(),
      );
    } else {
      // id不为空，为修改
      this.teacherService.complete(this.teacher.id, this.teacher).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('修改失败，请重试'),
        () => this.afterCallCompleted(),
      );
    }
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: TeacherDTO, operation: OperationType): void {
    this.loading = false;
    this.handleCancel();
    this.notification.emit({
      operation,
      data,
    });
    this.msg.success('保存成功!');
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }

  ngOnInit() {
    // 获取新建教师的默认密码
    this.configurationService.findById('6').subscribe(data => {
      this.defualtPW = data.value;
    });
  }
}
